package study.saas.common.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;

public class RedisUtils {

    private Jedis jedis;
    private static RedisUtils instance;

    private static Logger logger = LoggerFactory.getLogger(RedisUtils.class);

    private RedisUtils(String redisHost, Integer redisPort) {
        jedis = new Jedis(redisHost, redisPort);
    }

    public static RedisUtils getInstance(String redisHost, Integer redisPort) {
        // 单例模式双重校验锁
        // 第一次校验是否需要进入同步
        if(instance == null) {
            synchronized (RedisUtils.class) {
                // 第二次校验进入同步的过程中是否发生了线程抢占
                if(instance == null) {
                    instance = new RedisUtils(redisHost, redisPort);
                }
            }
        }
        return instance;
    }

    public void set(String key, String value) {
        jedis.set(key, value);
    }

    public void set(String key, String value, int time) {
        jedis.set(key, value);
        jedis.expire(key, time);
    }

    public String get(String key) {
        return jedis.get(key);
    }
}
